import { permission } from "@/api/login"
import router, { DynamicRoutes } from "@/router/index"
import dynamicRouter from "@/router/dynamic_router"
import { rescursionRouter, setDefaultRouter } from "@/util/recursion-router"

export default {
    namespaced: true,
    state: {
        permissionList: null,
        sidebarMenu: [],
        currentMenu: ''
    },
    getters: {},
    mutations: {
        SET_PERMISSION(state, routes) {
            state.permissionList = routes
        },
        CLEAR_PERMISSION(state) {
            state.permissionList = null;
        },
        SET_MENU(state, menu) {
            state.sidebarMenu = menu
        },
        CLEAR_MENU(state) {
            state.sidebarMenu = []
        },
        SET_CURRENT(state, curMenu) {
            state.currentMenu = curMenu
        },
        CLEAR_CURRENT(state) {
            state.curMenu = null;
        }
    },
    actions: {
        /* 生成权限路由表 */
        async FETCH_PERMISSION({ commit, state }) {
            let permissionRes = await permission()
            let permissionList = permissionRes;
            //筛选
            let routes = rescursionRouter(permissionList, dynamicRouter);
            let MainContainer = DynamicRoutes.find(v => v.path === "");
            let children = MainContainer.children;
            children.push(...routes)
            //生成菜单
            commit("SET_MENU", children);
            //设置默认路由
            setDefaultRouter([MainContainer]);
            //初始化路由
            let initialRoutes = router.options.routes;
            router.addRoutes(DynamicRoutes);
            commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutes])
            //规定默认选中的路由
            commit("SET_CURRENT", sessionStorage.getItem("currentIndex") || 'Person')
        }
    }
}